package utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * FreeMark模板工具类
 *
 * @author chenxd
 * @date 2019/05/20
 */
public class FreeMarkUtil {

   /**
    * FreeMark模板配置
    */
   private static final Configuration CONFIGURATION;

   /**
    * 配置模板路径
    */
   private static final String TEMPLATE_PATH = "/ftl";

   /**
    * 配置模板编码格式
    */
   private static final String ENCODING = "UTF-8";

   static {
      CONFIGURATION = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
      CONFIGURATION.setDefaultEncoding(ENCODING);
      CONFIGURATION.setClassForTemplateLoading(FreeMarkUtil.class,
              TEMPLATE_PATH);
   }

   private FreeMarkUtil() {
   }

   /**
    * @param templateName 调用的模板的路径名称
    * @param map          填充的参数
    * @return
    */
   public static String getTemplate(String templateName, Map<String, Object> map) {
      StringWriter out = new StringWriter();
      try {
         Template t = CONFIGURATION.getTemplate(templateName);
         t.process(map, out);
         out.flush();
         return out.getBuffer().toString();
      } catch (Exception e) {
         System.out.println("FreeMarkUtil文件读取失败:"+ e.getMessage());
      } finally {
         if (out != null) {
            try {
               out.close();
            } catch (IOException e) {
               System.out.println("FreeMarkUtil的out流关闭失败:"+ e.getMessage());
            }
         }
      }
      return null;
   }

   /**
    * @param templateName 调用的模板的路径名称
    * @return
    */
   public static String getTemplateObj(String templateName, Object object) {
      StringWriter out = new StringWriter();
      try {
         Template t = CONFIGURATION.getTemplate(templateName);
         t.process(object, out);
         out.flush();
         return out.getBuffer().toString();
      } catch (Exception e) {
         System.out.println("FreeMarkUtil文件读取失败:"+ e.getMessage());
      } finally {
         if (out != null) {
            try {
               out.close();
            } catch (IOException e) {
               System.out.println("FreeMarkUtil的out流关闭失败:"+ e.getMessage());
            }
         }
      }
      return null;
   }

}

